package group.sicher.core.web.validator.handler;

import group.sicher.core.encrypt.EncryptService;
import group.sicher.core.utils.SpringUtil;
import group.sicher.core.web.validator.annotation.Password;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author Donald
 * @description
 * @date 2019-06-11
 **/
@Slf4j
public class PasswordValidatorHandler implements ConstraintValidator<Password, String> {

    private String message;

    private Pattern pattern;

    private Class<? extends EncryptService>[] encryptServices;

    @Override
    public void initialize(Password constraintAnnotation) {
        this.message = constraintAnnotation.message();
        this.pattern = Pattern.compile(constraintAnnotation.regexp());
        this.encryptServices = constraintAnnotation.encrypt();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (this.encryptServices != null) {
            for (Class<? extends EncryptService> encryptService : encryptServices) {
                EncryptService encrypt = SpringUtil.getBean(encryptService);
                try {
                    return pattern.matcher(encrypt.decrypt(value)).matches();
                } catch (Exception e) {
                    log.error("密码解析错误: {}, {}", e.getMessage(), e);
                }
            }
        }

        return pattern.matcher(value).matches();
    }
}
